import {
    checkPermission,
    ensureGroupAndPlayerExist,
    formatCurrency,
    getConfig,
    getGroupPlayerList,
    getPlayerData,
    storagePlayerData
} from "../function/function.js";

export class Rob extends plugin {
    constructor() {
        super({
            name: '[Sm]抢劫',
            dsc: '尝试抢劫其他玩家的金币',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/](抢劫|打劫)$/, fnc: 'rob' }
            ]
        })
    }

    async rob(e) {
        try {
            if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
            const ID = [e.user_id, e.group_id];

            // 使用通用函数检查和初始化群组和玩家
            ensureGroupAndPlayerExist(ID[1], ID[0]);

            const userData = await getPlayerData(ID[1], ID[0]);
            const { currency, lastRobTime, master } = userData;

            const currentSecond = Math.floor(Date.now() / 1000);
            const config = getConfig();
            const robCooldown = config.rob.cooldown; // 从配置文件读取冷却时间

            if (!checkPermission(e) && currentSecond - (lastRobTime || 0) < robCooldown) {
                const remainingTime = robCooldown - (currentSecond - lastRobTime);
                return e.reply([`抢劫冷却中，剩余时间：${Math.floor(remainingTime / 3600)}小时${Math.floor((remainingTime % 3600) / 60)}分钟`]);
            }

            // 获取群成员信息
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);

            // 判断是否指定打劫目标
            let targetId;
            if (e.at) {
                ensureGroupAndPlayerExist(ID[1], e.at);
                targetId = e.at;
            } else {
                // 随机选择一个目标
                const groupPlayerList = getGroupPlayerList(ID[1]);
                targetId = groupPlayerList[Math.floor(Math.random() * groupPlayerList.length)].replace('.json', '');
            }

            if (targetId === ID[0]) return e.reply(['你不能抢劫自己']);
            if (targetId === master) return e.reply(['你不能抢劫你的主人']);

            const targetData = await getPlayerData(ID[1], targetId);
            const { currency: targetCurrency } = targetData;

            const successRate = config.rob.successRate; // 从配置文件读取成功率
            const penalty = config.rob.penalty; // 从配置文件读取惩罚比例

            const targetNickname = memberInfoList[targetId]?.nickname || '未知用户';

            if (Math.random() < successRate) {
                const robAmount = formatCurrency(Math.min(targetCurrency * 0.2, 100));
                userData.currency = formatCurrency(userData.currency + robAmount);
                targetData.currency = formatCurrency(targetData.currency - robAmount);
                await e.reply([`抢劫成功！你从${targetNickname}那里抢到了${robAmount}金币`]);
            } else {
                const penaltyAmount = formatCurrency(Math.min(currency * penalty, 50));
                userData.currency = formatCurrency(userData.currency - penaltyAmount);
                await e.reply([`抢劫失败！你被罚了${penaltyAmount}金币`]);
            }

            userData.lastRobTime = currentSecond;
            storagePlayerData(ID[1], ID[0], userData);
            storagePlayerData(ID[1], targetId, targetData);
        } catch (error) {
            logger.error('处理抢劫请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }
}
